package com.xxd;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

/**
 * @description:
 * @author: xuxd
 * @time: 2019/12/2 14:01
 */
public class SystemInfo {

    private static Map<String,String> sysNetInfo;
    public static final String EXPIRED = "expired";
    public static final String DATA_VERSION = "dataVersion.code";
    
    private SystemInfo(){}
    public static String getSysInfo(){
        StringBuffer sb = new StringBuffer();
        for (Object key :sysNetInfo.keySet()){
            sb.append(key+":"+sysNetInfo.get(key)+",");
        }
        return sb.toString();
    }

    public static Map<String,String> getSysInfoMap(){
        return sysNetInfo;
    }

    public static void updateInfo(String key,String value){
        sysNetInfo.put(key,value);
    }

    static {
        sysNetInfo = new HashMap<String,String>();
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface intf = (NetworkInterface) en.nextElement();
                Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()  && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
                        sysNetInfo.put(inetAddress.getHostAddress().toString(),getMac(inetAddress)) ;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getMac(InetAddress ip) throws SocketException {
        NetworkInterface ne=NetworkInterface.getByInetAddress(ip);
        byte[] mac=ne.getHardwareAddress();
        StringBuffer sb = new StringBuffer("");
        for(int i=0; i<mac.length; i++) {
            if(i!=0) {
                sb.append("-");
            }
            int temp = mac[i]&0xff;
            String str = Integer.toHexString(temp);
            if(str.length()==1) {
                sb.append("0"+str);
            }else {
                sb.append(str);
            }
        }
        return sb.toString().toUpperCase();
    }

    public static void main(String arg[]) throws Exception {
        System.out.println(SystemInfo.sysNetInfo );
    }
}
